import { getTaskUser, getWorkTask } from '@/api/flow/work';
import { getTemplateFields } from '@/api/flow/template';
import {
  tableType,
  layoutType,
  groupType
} from '@/components/Form/fieldType';

export default {
  data() {
    return {
      // 当前表单任务
      workDetails: {}
    };
  },

  methods: {
    // action data
    actionData(formFields) {
      const { task_node } = this.workDetails;
      const { id, name } = task_node;

      return {
        task_node: id,
        // 被沟通的人
        communicate_user: undefined,
        // # 被转办的人
        forward_user: undefined,
        choice_child: [],
        // 表单名称
        work_name: name,
        // 表单数据
        fields_data: formFields ? this.getFieldsDatas(formFields) : []
      };
    },

    // 获取表单提交数据
    getFieldsDatas(formFields) {
      const datas = formFields
        .map(({ field: f, value }) => ({
          field: f.id,
          field_value: { value }
        }));

      return datas;
    },

    // 获取工单信息
    getWorkTask() {
      return new Promise((resolve, reject) => {
        getTaskUser(this.tid)
          .then((response) => {
            console.log(response, this.tid, 'dadadada');
            this.workDetails = response;
            resolve(response);
          })
          .catch((err) => reject(err));
      });
    },

    // 获取表单信息
    getTemplateFields() {
      return new Promise((resolve, reject) => {
        // this.getLimits()
        //   .then(() => {
            this.getWorkTask()
              .then(() => {
                getTemplateFields(this.tid)
                  .then((response) => {
                    this.generateFormFields(response, this.formFields);
                    // this.generateFormFields(response, this.loanFormFields);
                    resolve(response);
                  })
                  .catch((err) => reject(err));
              })
              .catch((err) => reject(err));
          // })
          // .catch((err) => reject(err))
      });
    },

    // 生成表单
    generateFormFields(fields, formFields) {
      // get fields
      fields.forEach((fs) => this.layoutField(fs, formFields));
    },

    // 判断是否布局
    layoutField(fs, formFields) {
      // fields
      const { table } = tableType;

      // layout
      const { group } = groupType;
      const { ortc, explain } = layoutType;

      switch (fs.type) {
        case group.type:
          this.generateFormFields(fs.groups);
          break;

        case ortc.type:
          this.generateFormFields(fs.fields);
          break;

        case explain.type:
        case table.type:
          break;

        default:
          this.isExistField(fs, formFields);
      }
    },

    // 是否当前表单
    isExistField(field, formFields) {
      const index = formFields
        .findIndex(({ link }) => link === field.keys);

      if (index > -1) {
        formFields[index].field = field;
      }
    }
  }
};
